package com.ldw.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ldw.common.ErrorCode;
import com.ldw.mapper.SysUserMapper;
import com.ldw.pojo.SysUser;
import com.ldw.service.LoginService;
import com.ldw.utils.JWTUtils;
import com.ldw.utils.UserThreadLocal;
import com.ldw.vo.LoginParams;
import com.ldw.vo.Result;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    private static final String slat = "ldw!@#";

    @Override
    public Result login(LoginParams loginParam) {
        /*
         1.查询参数是否合法
         2.更具用户名和密码去user表中查询，是否存在
         3.如果不存在，登录失败
         4.如果存在，使用jwt生成token，返回给前端
         5.token放入redis当中，redis存放 token: user信息，设置过期时间
         */
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_ERROR.getCode(), ErrorCode.PARAMS_ERROR.getMsg());
        }
        password = DigestUtils.md5Hex(password + slat);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getAccount, account).eq(SysUser::getPassword, password);
        queryWrapper.select(SysUser::getAccount, SysUser::getId, SysUser::getAvatar, SysUser::getNickname);
        SysUser sysUser = sysUserMapper.selectOne(queryWrapper);
        if (sysUser == null) {
            return Result.fail(ErrorCode.ACCOUT_PAD_NOT_EXIST.getCode(), ErrorCode.ACCOUT_PAD_NOT_EXIST.getMsg());
        }
        UserThreadLocal.put(sysUser);
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_" + token, JSON.toJSONString(sysUser), 1000, TimeUnit.DAYS);
        return Result.success(token);
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_" + token);
        return Result.success(null);
    }
}

